﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using dotNails.CodeGen.Models;
using dotNails.Util;

namespace dotNails.UI {
	/// <summary>
	/// Interaction logic for ConventionConfig.xaml
	/// </summary>
	public partial class ConventionConfig : UserControl, IChildUserControl {
		private IUserControlParent _parent;
		protected ConfigData ConfigData = null;

		public ConventionConfig(IUserControlParent parent, ConfigData configData) {
			InitializeComponent();
			ConfigData = configData;
			_parent = parent;
		}

		public void Display() {
			ExcludedDBColumns.ItemsSource = ConfigData.Config.ExcludedColumns;
		}

		private void DeleteExcludedColumn(object sender, RoutedEventArgs e) {
			Button button = sender as Button;
			string deletedColumn = button != null ? button.CommandParameter.ToString() : string.Empty;
			ConfigData.Config.ExcludedColumns.RemoveAll(ec => ec.DBName == deletedColumn);
			
			ConfigData.SaveToFile();
			_parent.SetConfigData(ConfigData);
			LoadExcludedColumns();
		}

		private void NewExcludedColumn(object sender, RoutedEventArgs e) {
			txtExcludedColumn.Clear();
			AddExcludedColumnPanel.Visibility = Visibility.Visible;
			NewExcludedColumnPanel.Visibility = Visibility.Hidden;
			txtExcludedColumn.Focus();
		}

		private void CancelExcludedColumn(object sender, RoutedEventArgs e) {
			AddExcludedColumnPanel.Visibility = Visibility.Hidden;
			NewExcludedColumnPanel.Visibility = Visibility.Visible;
		}

		private void AddExcludedColumn(object sender, RoutedEventArgs e) {
			ConfigData.Config.ExcludedColumns.Add(new ExcludedColumn { DBName = txtExcludedColumn.Text });
			
			ConfigData.SaveToFile();
			_parent.SetConfigData(ConfigData);
			LoadExcludedColumns();
			
			AddExcludedColumnPanel.Visibility = Visibility.Hidden;
			NewExcludedColumnPanel.Visibility = Visibility.Visible;
		}

		private void LoadExcludedColumns() {
			ExcludedDBColumns.ItemsSource = null;
			ExcludedDBColumns.Items.Clear();
			ExcludedDBColumns.ItemsSource = ConfigData.Config.ExcludedColumns;
		}

		void GoBack(object sender, RoutedEventArgs e) {
			// Find all dbmls in the solution
			List<DbmlData> dbmls = AddInUtil.GetAllDBMLsInSolution(_parent.DTE);

			UserControl previousUserControl = new DatabaseList(_parent, dbmls);
			_parent.LoadUserControl(previousUserControl);
		}
	}
}
